<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          保存
        </el-button>
        <el-button v-loading="loading" type="warning" @click="goBack">
          取消
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-select v-model="catalog1Val" placeholder="一级分类" style="width: 150px" class="filter-item" @change="changeCatalog1">
          <el-option v-for="item in catalog1" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>

        <el-select v-model="catalog2Val" placeholder="二级分类" style="width: 150px" class="filter-item" @change="changeCatalog2">
          <el-option v-for="item in catalog2" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>

        <el-select v-model="catalog3Val" placeholder="三级分类" style="width: 150px" class="filter-item" @change="changeCatalog3">
          <el-option v-for="item in catalog3" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>

        <div class="postInfo-container">
          <el-form-item style="margin-top:30px; margin-bottom: 30px;" prop="title">
            商品名称  <el-input v-model="postForm.title" style="width: 350px" />
          </el-form-item>

          <el-form-item style="margin-bottom: 30px;" prop="description">
            商品简述  <el-input v-model="postForm.description" style="width: 350px" />
          </el-form-item>

          <el-form-item style="margin-bottom: 30px;" prop="originPrice">
            商品原价  <el-input v-model="postForm.originPrice" style="width: 350px" />
          </el-form-item>

          <el-form-item style="margin-bottom: 30px;" prop="price">
            商品现价  <el-input v-model="postForm.price" style="width: 350px" />
          </el-form-item>

          <el-form-item prop="imgUrl" style="margin-bottom: 30px;">
            默认图片  <el-upload
              class="avatar-uploader"
              action="http://localhost:8280/file"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="postForm.imgUrl" :src="postForm.imgUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>

          轮播图 <el-upload
            action="http://localhost:8280/file"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :file-list='swiperImagesArr'
            :on-success="uploadSwiperSuccess"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>

        </div>



        <el-button type="primary" style="margin-top: 20px;margin-bottom: 20px" size="small" icon="el-icon-edit" @click="handleAdd">
          添加销售属性
        </el-button>

        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="saleAttrList"
          border
          fit
          highlight-current-row
          style="width: 100%;"
        >
          <el-table-column label="序号" prop="id"  type="index" align="center" width="80">
          </el-table-column>

<!--          <el-table-column label="销售属性id" width="90">-->
<!--            <template slot-scope="{row}">-->
<!--              <span>{{ row.id }}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="销售属性名称" align="center">
            <template slot-scope="scope">
<!--              <span v-if="scope.row.baseSaleAttrKeyName">{{ scope.row.baseSaleAttrKeyName }}</span>-->

              <el-select v-model="scope.row.baseSaleAttrKeyName" placeholder="请选择" style="width: 150px" class="filter-item" @change="changeSaleAttrKey($event,scope.row)">
                <el-option v-for="item in baseSaleAttrKeyList" :key="item.id" :label="item.attrKeyName" :value="item.id" />
              </el-select>

            </template>
          </el-table-column>
          <el-table-column label="销售属性值" align="center">
            <template slot-scope="{row}">
              <el-tag class="tag"
                :key="saleAttrValue.saleAttrValueName"
                v-for="saleAttrValue in row.saleAttrValues"
                closable
                :disable-transitions="false"
                @close="handleClose(saleAttrValue,row)">
                {{saleAttrValue.saleAttrValueName}}
              </el-tag>

              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ 添加</el-button>

<!--              <span v-for="item in scope.row.saleAttrValues">-->
<!--                {{ item.saleAttrValueName }}-->
<!--              </span>-->
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
            <template slot-scope="scope">
                <el-button type="primary" size="small" icon="el-icon-edit" @click="handleDelete(scope.$index, scope.row)">
                  删除
                </el-button>

            </template>

          </el-table-column>
        </el-table>
        <el-form-item prop="detail" style="margin-bottom: 30px;margin-top:30px">
          <Tinymce ref="editor" v-model="postForm.detail" :height="400" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Sticky from '@/components/Sticky' // 粘性header组件
import { getSpu, saveSpu } from '@/api/spu'
import { getSaleAttr, getBaseSaleAttrKey } from '@/api/attributes'
import { getCatalog1, getCatalog2, getCatalog3 } from '@/api/catalog'

const defaultForm = {
  title: '',
  description: '',
  catalog3Id: undefined,
  originPrice: undefined,
  imgUrl: '',
  detail: '',
  swiperImages:[]
}

export default {
  name: 'SpuDetail',
  components: { Tinymce, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      spuId: null,
      catalog1: null,
      catalog2: null,
      catalog3: null,
      catalog1Val: '',
      catalog2Val: '',
      catalog3Val: '',
      postForm: Object.assign({}, defaultForm),
      loading: false,
      imgUrl: '',
      dialogImageUrl: '',
      dialogVisible: false,
      // file-list的格式必须是[name:"xxx",url:"xxx"]的格式
      swiperImagesArr:[],
      userListOptions: [],
      saleAttrList: [],
      baseSaleAttrKeyList: [],
      tableKey: 0,
      listLoading: false,
      rules: {
        // imgUrl: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        detail: [{ validator: validateRequire }]
      },
      tempRoute: {}
    }
  },
  computed: {},
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
      this.getSaleAttr(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
    this.getBaseSaleAttrKey()

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
    this.getCatalog1()
  },
  methods: {
    uploadSwiperSuccess(e){
      this.postForm.swiperImages.push({'imgUrl':e.data.url});
    },
    handleRemove(file, fileList) {

      // 等于 true 说明是刚刚上传的
      // 判断方法有很多 随便用一种。
      let isBlobImg = file.url.indexOf("blob") != -1;

      //检查删除了哪一张
      if (isBlobImg) {
        //blob是未取后台返回的图片地址的，直接从response.data.url中取图片地址
        this.postForm.swiperImages.forEach((item, i, arr) => {
          if (item.imgUrl === file.response.data.url) {
            this.postForm.swiperImages.splice(i, 1);
          }
        });
      } else {
        this.postForm.swiperImages.forEach((item, i, arr) => {
          if (item.imgUrl === file.url) {
            this.postForm.swiperImages.splice(i, 1);
          }
        });
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    handleAvatarSuccess(e) {
      this.imgUrl = e.data.url
      this.postForm.imgUrl = e.data.url
    },
    fetchData(id) {
      getSpu(id).then(r1 => {
        console.log("返回数据",r1.data)
        this.postForm = r1.data
        r1.data.swiperImages.forEach(item=>{
          this.swiperImagesArr.push({'url':item.imgUrl})
        })
        //设置分类下拉框
        this.catalog1Val = r1.data.catalog1Id
        getCatalog2(r1.data.catalog1Id).then(r2 => {
          this.catalog2 = r2.data
          this.catalog2Val = r1.data.catalog2Id
        })

        getCatalog3(r1.data.catalog2Id).then(r3 => {
          this.catalog3 = r3.data
          this.catalog3Val = r1.data.catalog3Id
        })
        //设置tag标签和title
        this.setTagsViewTitle()
        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = '编辑Spu'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = '编辑Spu'
      document.title = `${title} - ${this.postForm.id}`
    },
    //保存
    submitForm() {
      this.postForm.saleAttrList = this.saleAttrList
      console.log("表单：",this.postForm)
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true

          saveSpu(this.postForm).then(r1 => {
            this.loading = false
            this.$notify({
              title: '成功',
              message: '发布成功',
              type: 'success',
              duration: 2000
            })
            //返回列表页面
            this.goBack();
          })
        } else {
          return false
        }
      })
    },

    getCatalog1() {
      this.listLoading = true
      getCatalog1().then(r1 => {
        this.catalog1 = r1.data
        this.listLoading = false
      })
    },

    changeCatalog1(e) {
      this.listLoading = true
      getCatalog2(e).then(r1 => {
        this.catalog2 = r1.data
        this.catalog3 = null
        this.catalog2Val = ''
        this.catalog3Val = ''
        this.listLoading = false
      })
    },

    changeCatalog2(e) {
      this.listLoading = true
      getCatalog3(e).then(r1 => {
        this.catalog3 = r1.data
        this.catalog3Val = ''
        this.listLoading = false
      })
    },

    changeCatalog3(e) {
      this.postForm.catalog3Id = e
    },

    getSaleAttr(spuId){
      getSaleAttr(spuId).then(r1=>{
        //获取销售属性
        console.log("获取saleAttr",r1)
        this.saleAttrList = r1.data
      })
    },

    getBaseSaleAttrKey(){
      getBaseSaleAttrKey().then(r1=>{
        //获取基础销售属性-放入下拉框
        console.log("获取baseSaleAttr",r1.data)
        this.baseSaleAttrKeyList = r1.data
      })
    },

    changeSaleAttrKey(value,row){
      this.$set(row,'baseSaleAttrKeyId',value)
      //根据value获取label
      let resultArr = this.baseSaleAttrKeyList.find((item)=>{
        return item.id === value;
      });
      this.$set(row,'baseSaleAttrKeyName',resultArr.attrKeyName)
    },

    // 添加行
    handleAdd() {
      let row = {
        id: "",
        saleAttrKeyId: "",
        baseSaleAttrKeyName: "",
        saleAttrValues: []
      }
      this.saleAttrList.push(row)
    },

    // 删除行
    handleDelete(index, row) {
      this.saleAttrList.splice(index, 1)
    },

    //删除属性值标签
    handleClose(saleAttrValue,row) {
      row.saleAttrValues.splice(row.saleAttrValues.indexOf(saleAttrValue), 1);
    },

    showInput(row) {
      this.$set(row,'inputVisible',true)
      //todo 聚焦input不知道为什么不行
      // this.$nextTick(() => {
      //   console.log("input",this.$refs.saveTagInput)
      //   this.$refs.saveTagInput.focus();
      // });
    },

    handleInputConfirm(row) {
      let inputValue = row.inputValue;
      if (inputValue) {
        row.saleAttrValues.push({saleAttrValueName:inputValue});
      }
      this.$set(row,'inputVisible',false)
      this.$set(row,'inputValue','')
    },

    //关闭标签并返回列表页
    goBack(){
      this.$store.dispatch('tagsView/delView', this.$route).then(() => {
        this.$nextTick(() => {
          this.$router.replace({
            path: '/spu/list'
          })
        })
      })
    }


  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.news-textarea /deep/ {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

  /*图片*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  border: 1px solid #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  border: 1px solid #d9d9d9;
  width: 178px;
  height: 178px;
  display: block;
}
  .tag{
    margin-left:5px;
  }
</style>

